package b.h.y.bj.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.Date;

import b.h.y.bj.R;

/**
 * Created by YHB on 2016/1/7.
 */
public class RefreshListView extends ListView implements AbsListView.OnScrollListener, AdapterView.OnItemClickListener {

    public static final int STATE_PULL_REFRESH = 0; //下拉刷新
    public static final int STATE_RELEASE_REFRESH = 1; //松开刷新
    public static final int STATE_REFRESHING = 2; //正在刷新

    private int mCurrentState = STATE_PULL_REFRESH; //当前状态 默认是下拉刷新

    private boolean isLoadingMore = false; //是否正在加载更多

    private View mHeaderView;
    private int mHeaderViewHeight;
    private int startY = -1;//滑动的起点y坐标

    @ViewInject(R.id.tv_refresh_text)
    private TextView mTvText;

    @ViewInject(R.id.tv_refresh_date)
    private TextView mTvDate;

    @ViewInject(R.id.iv_refresh_img)
    private ImageView ivRefreshImage;

    @ViewInject(R.id.progressBar)
    private ProgressBar progressBar;
    private RotateAnimation animUp;
    private RotateAnimation animDown;

    private int mFooterViewHeight;
    private View mFooterView;

    public RefreshListView(Context context) {
        super(context);
        initHeaderView();
        initFooterView();
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initHeaderView();
        initFooterView();
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initHeaderView();
        initFooterView();
    }

    private void initHeaderView() {
        initArrowAnim();

        mHeaderView = View.inflate(getContext(), R.layout.refresh_header, null);

        ViewUtils.inject(this, mHeaderView);

        this.addHeaderView(mHeaderView);

        //隐藏下拉刷新
        mHeaderView.measure(0, 0);
        mHeaderViewHeight = mHeaderView.getMeasuredHeight();
        mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
    }

    /**
     * 初始化脚布局
     */
    private void initFooterView() {
        System.out.println("initFooterView");
        mFooterView = View.inflate(getContext(), R.layout.refresh_listview_footer, null);
        ViewUtils.inject(this, mFooterView);
        this.addFooterView(mFooterView);

        mFooterView.measure(0, 0);
        mFooterViewHeight = mFooterView.getMeasuredHeight();
        mFooterView.setPadding(0, -mFooterViewHeight, 0, 0); //隐藏脚布局

        this.setOnScrollListener(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = (int) ev.getRawY();
                break;

            case MotionEvent.ACTION_MOVE:
                if (startY == -1) {
                    startY = (int) ev.getRawY();
                }

                if (mCurrentState == STATE_REFRESHING) {
                    break;
                }

                int moveY = (int) ev.getRawY();
                int dy = moveY - startY;

                if (dy > 0 && getFirstVisiblePosition() == 0) { //只有下拉,且当前是第一个是item,才允许下拉
                    int paddingTop = dy - mHeaderViewHeight;
                    mHeaderView.setPadding(0, paddingTop, 0, 0);

                    if (paddingTop > 0 && mCurrentState != STATE_RELEASE_REFRESH) { //松开刷新
                        mCurrentState = STATE_RELEASE_REFRESH;
                        refreshState();
                    } else if (paddingTop < 0 && mCurrentState != STATE_PULL_REFRESH) { //改为下拉刷新状态
                        mCurrentState = STATE_PULL_REFRESH;
                        refreshState();
                    }
                    return true;
                }
                break;

            case MotionEvent.ACTION_UP:
                startY = -1;
                if (mCurrentState == STATE_RELEASE_REFRESH) {
                    mCurrentState = STATE_REFRESHING;
                    mHeaderView.setPadding(0, 0, 0, 0);
                } else if (mCurrentState == STATE_PULL_REFRESH) {
                    mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
                }
                refreshState();
                break;
        }

        return super.onTouchEvent(ev);
    }

    /**
     * 改变状态
     */
    private void refreshState() {
        switch (mCurrentState) {
            case STATE_PULL_REFRESH:
                mTvText.setText("下拉刷新");
                ivRefreshImage.setVisibility(View.VISIBLE);
                ivRefreshImage.startAnimation(animDown);
                progressBar.setVisibility(View.INVISIBLE);
                break;

            case STATE_RELEASE_REFRESH:
                mTvText.setText("松开刷新");
                ivRefreshImage.setVisibility(View.VISIBLE);
                ivRefreshImage.startAnimation(animUp);
                progressBar.setVisibility(View.INVISIBLE);
                break;

            case STATE_REFRESHING:
                mTvText.setText("正在刷新");
                ivRefreshImage.clearAnimation(); //必须先清除动画,才能隐藏
                ivRefreshImage.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.VISIBLE);

                if (refreshListener != null) {
                    refreshListener.onRrefresh();
                }

                break;
        }
    }

    /**
     * 初始化动画
     */
    private void initArrowAnim() {

        //向上的动画
        animUp = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animUp.setDuration(500);
        animUp.setFillAfter(true);

        //向下的动画
        animDown = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animDown.setDuration(500);
        animDown.setFillAfter(true);
    }

    /**
     * 收起下拉刷新的状态
     */
    public void OnRefreshComplete(boolean success) {
        if (isLoadingMore) { //加载更多完成
            System.out.println("加载更多结束");
            mFooterView.setPadding(0, -mFooterViewHeight, 0, 0);
            isLoadingMore = false;
        } else {
            mCurrentState = STATE_PULL_REFRESH;
            mTvText.setText("下拉刷新");
            ivRefreshImage.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.INVISIBLE);

            mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
        }

        if (success) {
            updateLastTime();
        }
    }

    /**
     * 更新最后的时间
     */
    public void updateLastTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        mTvDate.setText(time);
    }


    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        System.out.println("scrolling");
        if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_FLING) {
            if (getLastVisiblePosition() == getCount() - 1 && !isLoadingMore) { //滑动到最后了
                System.out.println("到底了");
                mFooterView.setPadding(0, 0, 0, 0); //显示出来
                setSelection(getCount() - 1); //并设置显示到最后一个
                isLoadingMore = true;

                if (refreshListener != null) {
                    refreshListener.onLoadMore();
                }
            }
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {

    }

    OnItemClickListener onItemClickListener;

    @Override
    public void setOnItemClickListener(OnItemClickListener listener) {
        super.setOnItemClickListener(this);
        onItemClickListener = listener;
    }

    OnRefreshListener refreshListener;

    public void setOnRefreshListener(OnRefreshListener refreshListener) {
        this.refreshListener = refreshListener;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (onItemClickListener != null) {
            onItemClickListener.onItemClick(adapterView, view, i - getHeaderViewsCount(), l);
        }
    }

    public interface OnRefreshListener {
        public void onRrefresh();

        public void onLoadMore();
    }
}
